package cn.jiedh.app.meiweidk.buried;

import android.app.IntentService;
import android.content.Intent;
import android.location.LocationManager;
import android.support.annotation.Nullable;
import android.util.Log;

import cn.jiedh.app.meiweidk.Utils.tool.DeviceUtils;
import cn.jiedh.app.meiweidk.Utils.tool.DeviceUuidFactory;
import cn.jiedh.app.meiweidk.Utils.tool.IntenetUtil;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.LocationUtil;
import cn.jiedh.app.meiweidk.Utils.tool.OverallData;
import cn.jiedh.app.meiweidk.Utils.tool.RSAUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.app.EnvConfig;
import cn.jiedh.app.meiweidk.app.MyApp;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPOutputStream;

/**
 * @name：埋点上传
 * @author：司马林
 * @phone：18423134135
 * @createTime：2017/10/27
 */

public class BuriedIntentService extends IntentService {

    private List<BuriedBean> list = new ArrayList<>();
    private String mobilePhone = "";

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public BuriedIntentService(String name) {
        super(name);
    }

    public BuriedIntentService() {
        super("");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent != null) {
            mobilePhone = intent.getStringExtra("mobilePhone");
            list.addAll(SPUtils.getBuriedList());
            L.i("进入了IntentService", list.toString());
            if (list != null && list.size() > 0) {
                request();
                SPUtils.deleteBuriedList();
            }
        }
    }

    private void request() {
        RequestParams params = new RequestParams(EnvConfig.BURIED_URL);
        DeviceUuidFactory factory = new DeviceUuidFactory(MyApp.mContext);
        Map<String, Object> map = new HashMap<>();
        //正式环境
//        String appKey = "TdHCcGQOYil5rgeO";
        //测试环境
        String platform = "Android";
        String channel = OverallData.getChannel();
        String uuid = factory.getDeviceUuid();
        String timestamp = System.currentTimeMillis() + "";
        map.put("appKey", EnvConfig.BURIED_APP_KEY);
        map.put("platform", platform);
        map.put("channel", channel);
        map.put("uuid", uuid);
        map.put("timestamp", timestamp);
        map.put("sign", sign(EnvConfig.BURIED_APP_KEY, platform, channel, uuid, timestamp));
        map.put("is_compress", "true");
        map.put("version", DeviceUtils.getVersionCode(MyApp.mContext) + "");
        map.put("mobilePhone", mobilePhone);
        map.put("deviceBrand", DeviceUtils.getDeviceBRAND());
        if (DeviceUtils.isTablet(MyApp.mContext)) {
            map.put("deviceType", "平板");
        } else {
            map.put("deviceType", "手机");
        }
        map.put("deviceModel", DeviceUtils.getDeviceName());
        map.put("OSVersion", "Android SDK版本号：" + DeviceUtils.getDeviceSDK());

        //Double[] doubles = LocationUtil.getGpsLocation(this.getApplicationContext(), (LocationManager) this.getApplication().getSystemService(LOCATION_SERVICE));

        Double[] doubles = LocationUtil.location;
        if (doubles != null) {
            map.put("latitude", doubles[0] + "");
            map.put("longitude", doubles[1] + "");
        }
        map.put("networkType", IntenetUtil.getNetworkState(this));
        map.put("wifiName", IntenetUtil.getConnectWifiSsid(this));
        boolean isAgency = IntenetUtil.isWifiProxy(this);
        map.put("isAgency", isAgency + "");
        if (isAgency) {
            map.put("agencyAddress", DeviceUtils.getHostIP());
        } else {
            map.put("agencyAddress", "");
        }
        map.put("agencyType", "");
        JSONObject object = new JSONObject();
        for (String key : map.keySet()) {
            try {
                object.put(key, map.get(key));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        params.addParameter("header", object.toString());

        JSONArray array = new JSONArray();
        if (list != null) {
            for (BuriedBean bean : list) {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("action", bean.getAction());
                    jsonObject.put("actName", bean.getActName());
                    jsonObject.put("actTime", bean.getActTime());
                    jsonObject.put("targetType", bean.getTargetType());
                    jsonObject.put("targetId", bean.getTargetId());
                    jsonObject.put("targetName", bean.getTargetName());
                    jsonObject.put("currentPage", bean.getCurrentPage());
                    jsonObject.put("isReact", bean.getIsReact());
                    jsonObject.put("isLogin", bean.getIsLogin());
                    jsonObject.put("stayTime", bean.getStayTime());
                    jsonObject.put("queryCondition", bean.getQueryCondition());
                    jsonObject.put("shareChannel", bean.getShareChannel());
                    jsonObject.put("verifyCode", bean.getVerifyCode());
                    jsonObject.put("inviteChannel", bean.getInviteChannel());
                    jsonObject.put("loanMoney", bean.getLoanMoney());
                    jsonObject.put("loanTerm", bean.getLoanTerm());
                    jsonObject.put("loanSort", bean.getLoanSort());
                    jsonObject.put("interestRate", bean.getInterestRate());
                    jsonObject.put("loanType", bean.getLoanType());
                    array.put(jsonObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            params.addParameter("reqData", compress(array.toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }
//        params.addParameter("reqData", array.toString());
        L.i("埋点请求参数------header：", params.getQueryStringParams().get(0).toString());
        L.i("埋点请求参数------reqData：", array.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("埋点请求成功", result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("埋点请求失败", ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private String sign(String appKey, String platform, String channel, String uuid, String timestamp) {
        String signStr = appKey + platform + channel + uuid + timestamp;
        try {
            return RSAUtils.sign(signStr.getBytes("UTF-8"), EnvConfig.BURIED_PRIVATE_KEY);
        } catch (Exception e) {
            L.e("埋点签名异常", e.toString());
        }
        return "";
    }

    public static String compress(String str) throws IOException {
        if (null == str || str.length() <= 0) {
            return str;
        }
        // 创建一个新的输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 使用默认缓冲区大小创建新的输出流
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        // 将字节写入此输出流
        gzip.write(str.getBytes("UTF-8"));  //因为后台默认字符集有可能是GBK字符集，所以此处需指定一个字符集
        gzip.close();
        // 使用指定的 charsetName，通过解码字节将缓冲区内容转换为字符串
        return out.toString("ISO-8859-1");
    }
}
